// ==========================================================================
// gin-sns自动生成业务逻辑层相关代码，只生成一次，按需修改,再次生成不会覆盖.
// date：2021-02-21 13:45:54 +0800 CST
// path: app/service/module/post_service.go
// author：jon
// ==========================================================================
package module

import (
	"errors"
	"gin-sns/app/dao/module/post"
	"gin-sns/app/dao/module/tag"
	"gin-sns/app/model"
	"gin-sns/app/model/constants"
	entitytagModel "gin-sns/app/model/module/entitytag"
	postModel "gin-sns/app/model/module/post"
	tagModel "gin-sns/app/model/module/tag"
	"strings"
	"time"

	"github.com/gin-gonic/gin"

	"gin-sns/app/ginframe/utils/convert"
	"gin-sns/app/ginframe/utils/page"
)

var PostService = newPostService()

func newPostService() *postService {
	return &postService{}
}

type postService struct {
}

//根据主键查询数据
func (s *postService) SelectRecordById(id int64) (*postModel.Entity, error) {
	return post.PostDao.SelectById(id)
}

//
func (s *postService) SelectRecordsIn(idarr []int64) ([]postModel.Entity, error) {

	list, err := post.PostDao.FindIn("id", idarr)
	if list != nil && len(list) > 0 {
		err = errors.New("not found")
		list = nil
	}
	return list, err
}

//根据主键删除数据
func (s *postService) DeleteRecordById(id int64) bool {
	return post.PostDao.DeleteById(id)
}

//批量删除数据记录
func (s *postService) DeleteRecordByIds(ids string) int64 {
	ida := convert.ToInt64Array(ids, ",")
	result, err := post.PostDao.DeleteBatch(ida...)
	if err != nil {
		return 0
	}
	return result
}

//添加数据
func (s *postService) AddSave(req *postModel.AddReq, ctx *gin.Context) (int64, error) {
	var entity postModel.Entity

	//entity.Id = req.Id
	entity.BlogId = req.BlogId
	entity.UserId = req.UserId
	entity.Title = req.Title
	entity.Content = req.Content
	entity.ExtraData = req.ExtraData
	entity.CountView = req.CountView
	entity.CountComment = req.CountComment
	entity.CountLike = req.CountLike
	entity.CountFavor = req.CountFavor
	entity.CountReward = req.CountReward
	entity.Status = req.Status
	entity.LastCommentTime = req.LastCommentTime
	entity.CreateTime = time.Now()
	//entity.CreateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user != nil {
	//	entity.CreateBy = user.LoginName
	//}

	_, err := post.PostDao.Insert(&entity)
	return entity.Id, err
}

//修改数据
func (s *postService) EditSave(req *postModel.EditReq, ctx *gin.Context) (int64, error) {
	entity := &postModel.Entity{Id: req.Id}
	ok, err := post.PostDao.FindOne(entity)

	if err != nil {
		return 0, err
	}

	if !ok {
		return 0, errors.New("数据不存在")
	}

	entity.BlogId = req.BlogId
	entity.UserId = req.UserId
	entity.Title = req.Title
	entity.Content = req.Content
	entity.ExtraData = req.ExtraData
	entity.CountView = req.CountView
	entity.CountComment = req.CountComment
	entity.CountLike = req.CountLike
	entity.CountFavor = req.CountFavor
	entity.CountReward = req.CountReward
	entity.Status = req.Status
	entity.LastCommentTime = req.LastCommentTime
	//entity.UpdateTime = time.Now()
	//entity.UpdateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user == nil {
	//	entity.UpdateBy = user.LoginName
	//}

	return post.PostDao.Update(entity)
}

//根据条件查询数据
func (s *postService) SelectListAll(params *postModel.SelectPageReq) ([]postModel.Entity, error) {
	return post.PostDao.SelectListAll(params)
}

//根据条件分页查询数据
func (s *postService) SelectListByPage(params *postModel.SelectPageReq) ([]postModel.Entity, *page.Paging, error) {
	return post.PostDao.SelectListByPage(params)
}

// 导出excel
func (s *postService) Export(param *postModel.SelectPageReq) (string, error) {
	head := []string{"", "博客id", "用户id", "标题", "内容", "扩展数据", "观看次数", "评论次数", "赞同次数", "收藏次数", "打赏次数", "0未审核 1正常状态 2审核未通过 3删除", "创建时间", "更新时间", "最后评论时间"}
	col := []string{"id", "blog_id", "user_id", "title", "content", "extra_data", "count_view", "count_comment", "count_like", "count_favor", "count_reward", "status", "create_time", "update_time", "last_comment_time"}
	return post.PostDao.SelectListExport(param, head, col)
}

// 获取文章对应的标签
func (s *postService) GetPostTags(postId int64) []tagModel.Entity {
	req := new(entitytagModel.SelectPageReq)
	req.EntityId = postId
	req.EntityType = constants.EntityTypePost

	postTags, _ := EntitytagService.SelectListAll(req)

	var tagIds []int64
	for _, postTag := range postTags {
		tagIds = append(tagIds, postTag.TagId)
	}

	//return cache.TagCache.GetList(tagIds)
	list, err := tag.TagDao.FindIn("id", tagIds)
	if err != nil || list == nil || len(list) == 0 {
		return nil
	}

	return list
}

// 分类文章列表
func (s *postService) GetCategoryPosts(categoryId int64, cursor int64) ([]postModel.Entity, int64) {

	req := new(postModel.SelectPageReq)
	req.BlogId = categoryId //BlogId - categoryId
	req.Status = model.ArticleTagStatusOk

	list, _ := s.SelectListAll(req)

	return list, 0
}

func (s *postService) GetTagPosts(tagId int64, cursor int64) (posts []postModel.Entity, nextCursor int64) {

	req := new(entitytagModel.SelectPageReq)
	req.TagId = tagId
	req.Status = model.PostTagStatusOk
	req.EntityType = constants.EntityTypePost
	//req.PageNum = cursor

	postTags, _ := EntitytagService.SelectListAll(req)

	var postIds []int64
	for _, postTag := range postTags {
		postIds = append(postIds, postTag.EntityId)
	}

	list, err := post.PostDao.FindIn("id", postIds)
	if err != nil || list == nil || len(list) == 0 {
		return nil, 0
	}

	return list, 0
}

// 发布文章
func (s *postService) Publish(userId int64, title, summary, content, contentType string, categoryId int64,
	tags []string, sourceUrl string, share bool) (p *postModel.Entity, err error) {

	title = strings.TrimSpace(title)
	content = strings.TrimSpace(content)

	if len(title) == 0 {
		return nil, errors.New("标题不能为空")
	}

	if len(sourceUrl) == 0 {
		return nil, errors.New("分享内容原文链接不能为空")
	}
	//} else {
	if len(content) == 0 {
		return nil, errors.New("内容不能为空")
	}
	//}
	entity := &postModel.Entity{
		UserId: userId,
		Title:  title,

		Content: content,
		//ContentType: contentType,
		//CategoryId:  categoryId,
		Status: model.ArticleStatusPublished,
		//Share:       share,
		//Tags:       strings.Join(tags, ","),
		//SourceUrl:  sourceUrl,
		CreateTime: time.Now(),
		UpdateTime: time.Now(),
	}

	_, err = post.PostDao.Insert(entity)
	if err != nil {
		return nil, err
	}

	//tagIds := TagService.GetOrCreates(tags)
	//EntitytagService.AddPostTags(post.Id, tagIds)

	//if err == nil {
	//	blogService.AnalyzePost(post)
	//}
	return entity, nil
}

// 修改文章
func (s *postService) Edit(postId int64, tags []string, title, content string) error {
	if len(title) == 0 {
		return errors.New("请输入标题")
	}
	if len(content) == 0 {
		return errors.New("请填写文章内容")
	}

	req := new(postModel.EditReq)
	req.Title = title
	req.Content = content
	rs, err := s.EditSave(req, nil) //c
	if err != nil || rs <= 0 {
		return err
	}

	//tagIds := TagService.GetOrCreates(tags)            // 创建文章对应标签
	//EntitytagService.DeletePostTags(postId)      // 先删掉所有的标签
	//EntitytagService.AddPostTags(postId, tagIds) // 然后重新添加标签

	//cache.PostTagCache.Invalidate(postId)
	return nil
}

// 最新文章
func (s *postService) GetNewestPosts(limit int) []postModel.Entity {
	list, _ := post.PostDao.GetNewestPosts(limit)
	return list
}

func (s *postService) GetUserNewestPosts(userId int64) []postModel.Entity {
	list, _ := post.PostDao.GetUserNewestPosts(userId)
	return list
}

func (s *postService) UpdateCommentInfo(postId, lastCommentTime int64) error {
	return post.PostDao.UpdateCommentInfo(postId, lastCommentTime)
}

// 浏览数+1
func (s *postService) IncrViewCount(postId int64) {
	post.PostDao.IncrViewCount(postId)
}

func (s *postService) IncrFavoriteCount(postId int64) {
	post.PostDao.IncrFavoriteCount(postId)
}

func (s *postService) DecrFavoriteCount(postId int64) {
	post.PostDao.DecrFavoriteCount(postId)
}

func (s *postService) IncrLikeCount(postId int64) {
	post.PostDao.IncrLikeCount(postId)
}

func (s *postService) DecrLikeCount(postId int64) {
	post.PostDao.DecrLikeCount(postId)
}
